package com.pigdogbay.anagramsolverpro;

import com.pigdogbay.anagramsolverpro.model.DictionaryData;
import com.pigdogbay.anagramsolverpro.presenters.AnagramPresenter;
import com.pigdogbay.androidutils.utils.ActivityUtils;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
		OnPageChangeListener {

	private static AnagramPresenter _AnagramPresenter;

	public static AnagramPresenter getAnagramPresenter() {
		return _AnagramPresenter;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		_AnagramPresenter = new AnagramPresenter(new DictionaryData(this));
		MainPagerAdapter adapter = new MainPagerAdapter(
				getSupportFragmentManager());
		ViewPager viewPager = (ViewPager) findViewById(R.id.main_viewpager);
		viewPager.setAdapter(adapter);
		viewPager.setOnPageChangeListener(this);
		try {
			checkAppRate();
			TipBox.showFirstTimeOnly(this);
		}
		catch (Exception e) {
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId())
		{
		case (R.id.menu_clear):
			_AnagramPresenter.Clear();
			break;
		case (R.id.menu_share):
			shareResults();
			break; 
		case (R.id.menu_show_tips):
			TipBox.show(this);
			break;
		default:
			return false;
		}
		return true;
	}

	/*
	 * OnPageChangeListener Methods
	 */
	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		if (arg0 != 0) {
			View focus = getCurrentFocus();
			if (focus != null) {
				ActivityUtils.hideKeyboard(this, focus.getWindowToken());
			}
		}
	}

	private void checkAppRate() {
		new com.pigdogbay.androidutils.apprate.AppRate(this)
				.setMinDaysUntilPrompt(7).setMinLaunchesUntilPrompt(5).init();
	}

	private void shareResults() {
		try {
			ActivityUtils.shareText(this, "Anagram Solver",
					_AnagramPresenter.getResults(),
					R.string.share_chooser_title);
		}
		catch (Exception e) {
			Toast.makeText(this, "Unable to share", Toast.LENGTH_SHORT).show();
		}
	}

}
